var ajaxGet = function (url, callback) {
    /*
    * 实现ajax函数，用GET方法请求一个URL
    * url是一个URL
    * callback是一个函数,在接收服务器响应后调用并传递参数给他
    * */
    var r = new XMLHttpRequest()
    r.open('GET', url, true)
    r.onreadystatechange = function (event) {
        if (r.readyState === 4) {
            callback(r.response)
        }
    }
    r.send()
}
//====================情景1：模拟获取
var url = 'http://152.136.245.180/uploads/tags.json'
ajaxGet(url, function (data) {
    console.log(data)
    var tags = JSON.parse(data)
    console.log(tags)
})

//==================场景2.1：用ajax获取数据,解析，伪装成我们的数据格式：ajax绑定按钮事件，实现登录
var pinsUrl = 'http://152.136.245.180/uploads/pins.json'
ajaxGet(pinsUrl, function (data) {
    var pins = JSON.parse(data)
    //pins变成全局变量
    window.pins = pins
})
//2.2
var keys = function (pins) {
    var l = []
    for (var i = 0; i < pins.length; i++) {
        var p = pins[i]
        var key = p.file.key
        l.push(key)
    }
}
//2.3 渲染界面
var addImageByKeys = function (keys) {
    for (var i = 0; i < keys.length; i++) {
        var k = keys[i]
        var url = 'http://img.hb.aicdn.com/' + k
        var tag = `<img src = ${url}>`
        var body = document.querySelector('body')
        body.insertAdjacentHTML('beforeend', tag)
    }
}

//场景3：模拟登陆函数
//不同于场景2：是一个request对象
var ajax = function (request) {
    var r = new XMLHttpRequest()
    r.open(request.method, request.url, true)
    if (request.contentType !== undefined) {
        r.setRequestHeader('Content-Type', request.contentType)
    }
    r.onreadystatechange = function (event) {
        if (r.readyState === 4) {
            request.callback(r.response)
        }
    }
    if (request.method === 'GET') {
        r.send()
    } else {
        r.send(request.data)
    }
}

var account = {
    'username': 'juran',
    password: '123',
}

var data = JSON.stringify(account)
var r = {
    method: 'GET',
    url: '/login',
    contentType: 'application/json',
    data: data,
    callback: function (response) {
        console.log('响应', response)
        var res = JSON.parse(response)
        if (res.success) {
            window.location.href = '/'
        } else {
            alert('登陆失败')
        }
    }
}

ajax(r)